package com.victory.calculator.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aries.ui.view.title.TitleBarView;
import com.bigkoo.pickerview.TimePickerView;
import com.victory.calculator.R;
import com.victory.calculator.api.Api;
import com.victory.calculator.entity.SubscriptionEntity;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.CacheMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.constant.ApiConstant;
import tech.com.commoncore.entity.BaseTResp;
import tech.com.commoncore.utils.DataUtils;
import tech.com.commoncore.utils.OnNoDoubleClickListener;
import tech.com.commoncore.utils.ToastUtil;

/**
 * 认购份额计算
 */
public class SubscriptionActivity extends BaseTitleActivity {


    private EditText etSubscriptionAmount;
    private EditText etNetWorth;
    private EditText etSubscriptionRates;
    private EditText etInterbankInterestRate;
    private TextView tvSubscriptionDate;
    private TextView tvDateOfEstablishment;
    private Button btnStart;
    private Button btnAgain;
    private TextView tvSubscriptionFee;
    private TextView tvInterestCarryForward;
    private TextView tvSubscriptionQuota;
    private TextView tvStartTime;
    private TextView tvEndTime;

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText(getResources().getString(R.string.calculator_subscription_title));
    }

    @Override
    public int getContentLayout() {
        return R.layout.calculator_activity_subscription;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //认购金额
        etSubscriptionAmount = (EditText) findViewById(R.id.et_subscription_amount);
        //单位份额基金净值
        etNetWorth = (EditText) findViewById(R.id.et_net_worth);
        //认购费率
        etSubscriptionRates = (EditText) findViewById(R.id.et_subscription_rates);
        //同业存款利率
        etInterbankInterestRate = (EditText) findViewById(R.id.et_interbank_interest_rate);
        //认购日期
        tvSubscriptionDate = (TextView) findViewById(R.id.tv_subscription_date);
        //成立日期
        tvDateOfEstablishment = (TextView) findViewById(R.id.tv_date_of_establishment);
        //认购手续费
        tvSubscriptionFee = (TextView) findViewById(R.id.tv_subscription_fee);
        //认购期利息结转
        tvInterestCarryForward = (TextView) findViewById(R.id.tv_interest_carry_forward);
        //认购份额
        tvSubscriptionQuota = (TextView) findViewById(R.id.tv_subscription_quota);
        tvStartTime = (TextView) findViewById(R.id.tv_start_time);
        tvEndTime = (TextView) findViewById(R.id.tv_end_time);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnAgain = (Button) findViewById(R.id.btn_again);

        btnStart.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {

                if (DataUtils.isEmpty(etSubscriptionAmount.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_amount));
                    return;
                }
                if (DataUtils.isEmpty(etNetWorth.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_net_worth));
                    return;
                }
                if (DataUtils.isEmpty(etSubscriptionRates.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_rates));
                    return;
                }
                if (DataUtils.isEmpty(etInterbankInterestRate.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_interbank_interest_rate));
                    return;
                }
                if (DataUtils.isEmpty(tvStartTime.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_start_time));
                    return;
                }
                if (DataUtils.isEmpty(tvEndTime.getText())) {
                    ToastUtil.show(getResources().getString(R.string.calculator_subscription_et_end_time));
                    return;
                }
                String price = etSubscriptionAmount.getText().toString().trim();
                String fund_value = etNetWorth.getText().toString().trim();
                String rate = etSubscriptionRates.getText().toString().trim();
                String interest_rate = etInterbankInterestRate.getText().toString().trim();
                String start_time = tvStartTime.getText().toString().trim();
                String end_time = tvEndTime.getText().toString().trim();
                if (Double.parseDouble(rate)>0){
                    if (Double.parseDouble(rate)<=1.5){
                        showLoading();
                        start(price, fund_value, rate, interest_rate,start_time,end_time);
                    }else {
                        ToastUtil.show(getResources().getString(R.string.calculator_rate));
                        return;
                    }
                }else {
                    ToastUtil.show(getResources().getString(R.string.calculator_rate));
                    return;
                }

            }
        });
        btnAgain.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        etSubscriptionAmount.setText("");
                        etNetWorth.setText("");
                        etSubscriptionRates.setText("");
                        etInterbankInterestRate.setText("");
                        tvSubscriptionFee.setText("");
                        tvInterestCarryForward.setText("");
                        tvSubscriptionQuota.setText("");
                    }
                });
            }
        });
        //认购日期
        tvStartTime.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                pickDate(0);
            }
        });
        //成立日期
        tvEndTime.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                pickDate(1);
            }
        });

    }

    private void start(String price, String fund_value, String rate, String interest_rate,String start, String end) {
        ViseHttp.GET(Api.SUBSCRIPTION_URL)
                .baseUrl(ApiConstant.BASE_URL)
                .addParam("price", price)
                .addParam("fund_value", fund_value)
                .addParam("rate", rate)
                .addParam("interest_rate", interest_rate)
                .addParam("start", start)
                .addParam("end", end)
                .setHttpCache(true)
                .cacheMode(CacheMode.FIRST_REMOTE)
                .request(new ACallback<BaseTResp<SubscriptionEntity>>() {
                    @Override
                    public void onSuccess(final tech.com.commoncore.entity.BaseTResp<SubscriptionEntity> data) {
                        try {
                            if (data.data != null) {
                                hideLoading();
                                new Handler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvSubscriptionFee.setText(data.data.getSubscription_fee());
                                        tvInterestCarryForward.setText(data.data.getInterest() + "");
                                        tvSubscriptionQuota.setText(data.data.getSubscription_share() + "");
                                    }
                                });
                            } else {
                                hideLoading();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        hideLoading();
                    }
                });
    }

    private void pickDate(final int i) {
        TimePickerView pvTime = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = getTime(date);
                if (i==0) {
                    tvStartTime.setText(time);
                }else {
                    tvEndTime.setText(time);
                }
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(getResources().getColor(R.color.colorPrimary))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.colorPrimary))//取消按钮文字颜色
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    //可根据需要自行截取数据显示
    public String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
